<template>
  <el-container class="home-container">
    <el-header><!-- 头部区 -->
        <img style="font-size: 24px; margin-left: 20px;" :src="require('@/assets/cy.png')">
        <span style="font-size: 24px; margin-right: 78%;">管理系统</span>
        <el-dropdown>
          <el-button type="primary">
            {{ currentUser }},欢迎您！
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="setInfo()">个人信息</el-dropdown-item>
              <el-dropdown-item type="info" @click="logout" style="margin-right: 0px;">切换账号</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
    </el-header>
    <el-container>
      <!-- 侧边栏 -->
      <el-aside :width="isCollapse ? '64px' : '240px'">
      <!-- 折叠条 -->
      <div class="toggle-button" @click="toggleCollapse()">|||</div>
      <!-- 侧边栏菜单区域 -->
        <el-menu background-color="#34184f" text-color="#fff"
          active-text-color="#FFC0CB" :unique-opened="true"
          :collapse="isCollapse" :collapse-transition="false"
          :router="true" :default-active="paths">
        <el-menu-item index="users">
          <el-icon><DataLine /></el-icon>
            <span style="font-size: 18px;">首页</span>
          </el-menu-item>
        <el-sub-menu :index="item1.id+''" v-for="item1 in menuList" :key="item1.id">
          <template #title>
            <el-icon><UserFilled /></el-icon>
            <span>{{item1.menus}}</span>
          </template>
          <el-sub-menu :index="item1.id+'-'+item2.id" v-for="item2 in item1.children" :key="item2.id">
            <template #title>
              <el-icon><Checked /></el-icon>
              <span>{{item2.menus}}</span>
            </template>
<!--            <el-sub-menu :index="item2.id+'-'+item3.id" v-for="item3 in item2.children" :key="item3.id">-->
<!--            <template #title>-->
<!--              <el-icon><Checked /></el-icon>-->
<!--              <span>{{item3.menus}}</span>-->
<!--            </template>-->
            <el-menu-item :index="item2.id+'-'+item3.id" v-for="item3 in item2.children" :key="item3.id">
            <template #title>
              <el-icon><Checked /></el-icon>
              <span>{{item3.menus}}</span>
            </template>
          </el-menu-item>
<!--          </el-sub-menu>-->
          </el-sub-menu>
        </el-sub-menu>
        <el-menu-item index="im">
          <el-icon><DataLine /></el-icon>
            <span style="font-size: 14px;">IM即时通讯</span>
        </el-menu-item>
        <el-menu-item index="update_down">
          <el-icon><DataLine /></el-icon>
            <span style="font-size: 14px;">上传下载</span>
        </el-menu-item>
        <el-menu-item index="update_user">
          <el-icon><DataLine /></el-icon>
            <span style="font-size: 14px;">历史修改</span>
        </el-menu-item>
        <el-menu-item index="tu_biao">
          <el-icon><DataLine /></el-icon>
            <span style="font-size: 14px;">图表</span>
        </el-menu-item>
       </el-menu>
      </el-aside>
      <!-- 右侧内容主体 -->
      <el-main>
             <router-view/>
      </el-main>
    </el-container>
                <!-- 分配角色的对话框 -->
      <el-dialog title="修改資料" v-model="setRoleDialogVisible" width="20%">
          <div style="margin-bottom: 20px;">
          <p>当前用户：{{currentUser}}</p>
            </div>
          <div style="margin-bottom: 20px;">
            <p style="display: inline-block;">用戶頭像：</p>
            <el-upload
              style="display: inline-block;"
              class="avatar-uploader"
              action="http://127.0.0.1:8000/upload_image/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 50px; height: 50px;"/>
            </el-upload>
          </div>
          <div style="margin-bottom: 20px;">
          <p>
            更改性別：
            <el-select v-model="selectsex" placeholder="请选择">
                <el-option v-for="sex in ['男','女']" :key="sex"
                    :label="sex" :value="sex">
                </el-option>
            </el-select>
          </p>
            </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveInfo(currentUser)">确 定</el-button>
            </span>
          </template>
      </el-dialog>
  </el-container>
</template>

<script>
import { defineComponent } from 'vue'
import { UserFilled, Checked, DataLine} from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'
import {ElMessage} from "element-plus";
export default defineComponent({
  setup() {
      const route = useRoute()
      const paths = route.fullPath.split("/")[1]
      return {
        paths,
      }
  },
  data() {
  return {
    setRoleDialogVisible: false,
    currentUser: localStorage.getItem('account'),
    imageUrl: 'http://127.0.0.1/image/'+localStorage.getItem('account')+'.jpg',
    menuList: [],
    isCollapse: false,
    selectsex:""
  }
  },
  components: {
    UserFilled,
    Checked,
    DataLine,
  },
  created() {
    this.getMenuList()
  },
  methods: {
    logout() {
      localStorage.clear() // 删除存储的 token
      this.$router.push('/')
    },
    async getMenuList() {
      try {
        const response = await this.$http.post('/menus/', {'cardid': localStorage.getItem('cardid')})
        this.menuList = response.data
        console.log(response.data)
      } catch (error) {
        console.log(error)
      }
    },
    //点击按钮，切换菜单的折叠与展开
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    async setInfo() {
      try {
        const response = await this.$http.post('/getrole/');
        console.log(response)
        //显示对话框
        this.setRoleDialogVisible = true;
      } catch (error) {
        console.error(error)
        ElMessage({message: '获取失败！'});
      }
    },
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      async beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        // 创建一个包含文件和额外数据的 FormData 对象
        const formData = new FormData();
        formData.append('file', file);
        formData.append('username', this.currentUser);

        // 发送 POST 请求
        await this.$http.post('/upload_image/', formData, {
          headers: {'Content-Type': 'multipart/form-data'}
        }).then((response) => {
          console.log(response)
        }).catch(() => {
          this.$message.error('上传头像失败');
        });
        return isLt2M && isJPG;
      },
        // 点击按钮保存
    async saveInfo(cardid) {
      try {
        const response = await this.$http.post('/imuserinfo/', {sex: this.selectsex, "cardid": cardid,'imageUrl':'http://127.0.0.1/image/'+localStorage.getItem('account')+'.jpg'});
        console.log(response);
        ElMessage.success('更新成功！');
        this.selectsex = '';//清空本次选择，避免影响下次
        this.setRoleDialogVisible = false;//关闭对话框
      } catch (error) {
        console.error(error)
        ElMessage.error({message: '更新失败！'});
      }
    },
  }
})
</script>

<style lang="less" scoped>
.home-container {
  height: 100%;
}
.el-header {
  background-color: #230544;
  display: flex; //设置显示为flex布局
  justify-content: space-between; //设置为flex左右布局
  padding-left: 0; //左内边距为0（Logo贴左边）
  align-items: center; //元素上下居中（防止右边按钮贴上下边）
  color: #F5F5F5;
  font-size: 20px;
  > div {
    //内嵌的div样式
    display: flex;
    align-items: center; //Logo和文字上下居中
    span {
      margin-left: 15px; //文字左侧设置间距，防止与Logo紧贴
    }
  }
}
.el-aside {
  background-color: #34184f;
  .el-menu{
    border-right: none;
  }
}
.el-main {
  background-color: #eaedf1;
}
.toggle-button{
  background-color: #3e176c;//背景色(浅灰)
  font-size: 10px;//字体大小10像素
  line-height: 24px;//行高24像素
  color: #fff;//字体颜色白色
  text-align: center;//字体居中
  letter-spacing: 0.2em;//字体之间的距离
  cursor: pointer;//鼠标的形状（手形）
}
.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>

